package LeetCode;

public class LC_405_ConvertaNumbertoHexadecimal {

    public static void main(String[] args) {

    }

    static class Solution {
        char[] map = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

        public String toHex(int num) {
            if (num == 0) return "0";
            StringBuilder result = new StringBuilder();
            while (num != 0) {
                result.insert(0, map[(num & 0xF)]);
                num = (num >>> 4);
            }
            return result.toString();
        }

    }

    static class Solution_2 {
        public String toHex(int num) {
            if (num == 0) return "0";
            int MAX = 32;
            boolean isNegative = false;
            int bits[] = new int[MAX];
            if (num < 0) {
                isNegative = true;
                bits[MAX - 1] = 1;
                num = -num;
            }

            int i = 0;
            while (num > 0) {
                bits[i++] = num % 2;
                num /= 2;
            }
            if (isNegative) {
                for (int j = 0; j < bits.length - 1; j++) bits[j] = (bits[j] + 1) % 2;
                int digit = 1;
                int res = 0;
                for (int j = 0; j < bits.length - 1; j++) {
                    res = bits[j] + digit;
                    bits[j] = res % 2;
                    digit = res / 2;
                }
            }
            StringBuilder ret = new StringBuilder();
            for (int j = 0; j < bits.length; j += 4) {
                int data = 0;
                for (int j2 = 0; j2 < 4; j2++)
                    data += bits[j + j2] * (1 << j2);
                ret.insert(0, String.format("%x", data));
            }
            for (int j = 0; j < ret.length(); j++) {
                if (ret.charAt(j) != '0') {
                    ret = new StringBuilder(ret.substring(j));
                    break;
                }
            }
            return ret.toString();
        }

    }
}